package com.donger.auth.component;


import cn.hutool.core.util.StrUtil;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.PatternMatchUtils;
import org.springframework.util.StringUtils;

import java.util.Optional;
import java.util.function.Function;

/**
 * 权限判断工具
 *
 * @author Aeizzz
 */

@Component("pms")
public class PermissionService {

    /**
     * 判断接口是否有xxx:xxx权限
     *
     * @param permission 权限名
     * @return true 有权限   false 没有权限
     */
    public boolean hasPermission(String permission) {
        return Optional.ofNullable(permission)
                .filter(StrUtil::isNotBlank)
                .map(isCurrentUserInRole()).orElse(false);
    }

    /**
     * 当前用户是否有当前权限
     *
     * @return Function<String                               ,                                                               Boolean> 当前用户是否有权限的判断方法
     */
    private Function<String, Boolean> isCurrentUserInRole() {
        SecurityContext securityContext = SecurityContextHolder.getContext();
        return p -> Optional.ofNullable(securityContext.getAuthentication())
                .map(authentication -> authentication.getAuthorities().stream()
                        .map(GrantedAuthority::getAuthority)
                        .filter(StringUtils::hasText)
                        .anyMatch(x -> PatternMatchUtils.simpleMatch(p, x)))
                .orElse(false);
    }
}
